package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {


    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.secret}")
    private String appSecret;

    //获取访问token的api地址
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    //获取手机号的spi地址
    private static final String POST_PHONE_API_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    //小程序登录的api地址
    private static final String GET_OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 获取小程序基本程序
     */
    public Map<String,Object> getAppConfig(){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("appid",appId);
        paramMap.put("secret",appSecret);
        return paramMap;
    }

    /**
     * 获取微信小程序的访问token
     * @return
     */
    private String getAccessToken() {
        Map<String, Object> paramMap = this.getAppConfig();
        paramMap.put("grant_type","client_credential");
        String result = HttpUtil.get(GET_ACCESS_TOKEN_URL, paramMap);
        if (StringUtils.isBlank( result)) {
            throw new BaseException("获取微信小程序的访问token失败");
        }
        JSONObject jsonObject= JSONObject.parse(result);
        return jsonObject.getString("access_token");

    }

    /**
     * 获取微信小程序的openId
     * @param code
     * @return
     */

    @Override
    public String getOpenId(String code) {
        Map<String, Object> paramMap = this.getAppConfig();
        paramMap.put("grant_type","authorization_code");
        paramMap.put("js_code",code);

        String result = HttpUtil.get(GET_OPEN_ID_URL, paramMap);
        if (StringUtils.isBlank( result)) {
            throw new BaseException("获取微信小程序的openId失败");
        }
        JSONObject jsonObject= JSONObject.parseObject(result);
        return jsonObject.getString("openid");
    }

    /**
     * 根据临时凭证码获取手机号码
     *
     * @param code
     */
    @Override
    public String getPhone(String code) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("code",code);
        String requestBody = JSON.toJSONString(paramMap);
        String result = HttpUtil.post(POST_PHONE_API_URL + this.getAccessToken(),requestBody);
        if (StrUtil.isBlank(result)) {
            throw new BaseException("获取手机号失败");
        }

        JSONObject jsonObject = JSONObject.parseObject(result);

        // 检查微信接口返回的错误码
        if (jsonObject.containsKey("errcode") && jsonObject.getIntValue("errcode") != 0) {
            int errCode = jsonObject.getIntValue("errcode");
            String errMsg = jsonObject.getString("errmsg");
            if (errCode == 40029) {
                throw new BaseException("临时凭证code无效或已过期，请重新调用wx.login获取新的code");
            } else if (errCode == 47001) {
                throw new BaseException("数据格式错误，请检查请求参数");
            } else {
                throw new BaseException("获取手机号失败: " + errMsg + " (错误码: " + errCode + ")");
            }
        }

        // 获取手机号信息
        if (jsonObject.containsKey("phone_info")) {
            JSONObject phoneObject = jsonObject.getJSONObject("phone_info");
            return phoneObject.getString("phoneNumber");
        }

        return null;
    }

}
